package inventory.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import inventory.common.CommonConstants;
import inventory.common.ResultData;
import inventory.entity.PermissionRecord;
import inventory.entity.User;
import inventory.entity.bo.UserPermissionBo;
import inventory.service.PermissionRecordService;
import inventory.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Api(tags = "权限相关")
@RestController
@RequestMapping(CommonConstants.PERMISSION_PREFIX)
public class PermissionController {

    @Resource
    PermissionRecordService permissionRecordService;
    @Resource
    UserService userService;

    /**
     * 根据workId查询权限列表
     * @param workId
     * @return
     */
    @RequiresPermissions("permission:operate")
    @ApiOperation("根据用户workId查询权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workId",value = "用户id"),
            @ApiImplicitParam(name = "managerId",value = "管理员id")
    })
    @RequestMapping(value = "/queryPermissionByWorkId",method = RequestMethod.GET)
    public ResultData queryPermissionByWorkId(String managerId,String workId) {
        //判断用户 是否 存在
        User user = userService.selectOne(new EntityWrapper<User>().eq("work_id", workId));
        if (user==null){
            return new ResultData().FAILD().setResultIns("用户不存在");
        }
        //判断用户是否为该管理员的 员工
        if (!userService.queryManagerByUserId(user.getUserId()).getManagerId().equals(managerId)){
            return new ResultData().FAILD().setResultIns("用户不是该管理员的员工");
        }
        List<PermissionRecord> permissionList = permissionRecordService.selectList(new EntityWrapper<PermissionRecord>().eq("user_id", user.getUserId()));
        return new ResultData().OK().setObjs(permissionList);
    }

    /**
     * 根据userId和permissionListId删除用户的权限
     * @param userId
     * @param permissionListId
     * @return
     */
    @Deprecated
    @RequiresPermissions("permission:operate")
    @ApiOperation("根据用户id删除权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id"),
            @ApiImplicitParam(name = "permissionListId",value = "权限id，多个的话用英文逗号分隔")
    })
    @RequestMapping(value = "/deletePermissionByUserId", method = RequestMethod.POST)
    public ResultData deletePermissionByUserId(String userId, String permissionListId) {
        String[] permissionListIds =  permissionListId.split(",");
        List<String> list = Arrays.asList(permissionListIds);
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",userId);
        for (String item: list) {
            map.put("permission_list_id", item);
            permissionRecordService.deleteByMap(map);
        }
        return new ResultData().OK();
    }

    /**
     * 添加用户权限
     * @param userId
     * @param permissionListId
     * @return
     */
    @Deprecated
    @RequiresPermissions("permission:operate")
    @ApiOperation("根据用户id新增权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id"),
            @ApiImplicitParam(name = "permissionListId",value = "权限id，多个的话用英文逗号分隔")
    })
    @RequestMapping(value = "/addPermissionByUserId", method = RequestMethod.POST)
    public ResultData addPermissionByUserId(String userId, String permissionListId){
        String[] permissionListIds =  permissionListId.split(",");
        List<String> list = Arrays.asList(permissionListIds);

        Map<String,Object> map = new HashMap<>();   //map用来select
        map.put("user_id", userId);

        PermissionRecord permissionRecord = new PermissionRecord();     //这个对象用来insert
        permissionRecord.setUserId(userId);

        for (String item: list) {
            map.put("permission_list_id", item);

            //先查询user是否以及有对应权限
            List<PermissionRecord> checkPermissionRecord = permissionRecordService.selectByMap(map);
            //如果有记录则跳过本次循环
            if (checkPermissionRecord.size()!=0){
                continue;
            }

            permissionRecord.setPermissionListId(new Integer(item));
            //如果没有记录a则插入
            permissionRecord.setPermRecId(UUID.randomUUID().toString().replaceAll("-", ""));
            permissionRecordService.insert(permissionRecord);

        }

        return new ResultData().OK();
    }

    @RequiresPermissions("permission:operate")
    @ApiOperation("根据workId更新用户权限")
    @PostMapping(value = "updatePermissionByWorkId")
    public ResultData updatePermissionByUserId(@RequestBody UserPermissionBo userPermissionBo){
        //判断用户 是否 存在
        User user = userService.selectOne(new EntityWrapper<User>().eq("work_id", userPermissionBo.getWorkId()));
        if (user==null){
            return new ResultData().FAILD().setResultIns("用户不存在");
        }
        //判断用户是否为该管理员的 员工
        if (!userService.queryManagerByUserId(user.getUserId()).getManagerId().equals(userPermissionBo.getManagerId())){
            return new ResultData().FAILD().setResultIns("用户不是该管理员的员工");
        }

        boolean res = permissionRecordService.delete(new EntityWrapper<PermissionRecord>().eq("user_id", user.getUserId()));
        if (res){

            PermissionRecord permissionRecord = new PermissionRecord();     //这个对象用来insert
            permissionRecord.setUserId(user.getUserId());

            for (Integer item: userPermissionBo.getPermissionIdList()) {

                //如果没有记录a则插入
                permissionRecord.setPermRecId(UUID.randomUUID().toString().replaceAll("-", ""));
                permissionRecord.setPermissionListId(item);
                permissionRecordService.insert(permissionRecord);

            }

            return new ResultData().OK();
        }else {
            return new ResultData().FAILD();
        }

    }


}
